package com.example.manager.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.example.manager.entity.Course;
import com.example.manager.repository.CourseRepository;

@Service
@Transactional
public class CourseServiceImpl implements CourseService {
	
	@Autowired
	private CourseRepository courseRepository;
	
	@Override
	public String addCourse(Course cou) {
		String code = cou.getCode();
		String name = cou.getName();
		
		if(code==null||code.length()==0||name==null||name.length()==0||cou.getCredit()==null) {
			return "incomplete info";
		}
		courseRepository.save(cou);
		return "success";
	}

	@Override
	public String deleteCourse(Integer id) {
		if(courseRepository.existsById(id)) {
			courseRepository.deleteById(id);
			return "success";
		}
		
		return "fail";
	}

	@Override
	public String editCourse(Course cou) {
		int id = cou.getId();
		String code = cou.getCode();
		String name = cou.getName();
		Double credit = cou.getCredit();
		System.out.println(id+"   "+code+"   "+name+"   "+credit);
		Course c = courseRepository.getOne(id);
		if(code==null||code.length()==0||name ==null||name.length()==0||cou.getCredit()==null) {
			return "incomplete info";
		}
		c.setName(name);
		c.setCode(code);
		c.setCredit(credit);
		
		if(courseRepository.existsById(id)) {
			courseRepository.save(c);
			return "success";
		}
		return "fail";
	}
	
	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public List<Course> findAllCourse() {
		return courseRepository.findAll();
		
	}

	@Override
	public Course getByCode(String code) {
		return courseRepository.getByCode(code);
	}

	@Override
	public Course getById(Integer id) {
		return courseRepository.getOne(id);
	}

}
